package mo.golden;

public class L01_06 {

    public String compressString(String S) {
        if (S == null || S.length() == 0) {
            return S;
        }
        int n = S.length();
        StringBuilder builder = new StringBuilder();
        char pre = S.charAt(0);
        int count = 1;
        for (int i = 1; i < n; i++) {
            if (S.charAt(i) == pre) {
                count++;
            } else {
                builder.append(pre).append(count);
                pre = S.charAt(i);
                count = 1;
            }
        }
        builder.append(pre).append(count);
        String compressed = builder.toString();
        if (compressed.length() < S.length()) {
            return compressed;
        }
        return S;
    }

    public static void main(String[] args) {
        L01_06 test = new L01_06();
        System.out.println(test.compressString("aabcccccaaa"));
    }

}
